package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.Flow;
import com.mp.approvalreq.entity.Request;
import com.mp.approvalreq.service.ApprovalOperateServicePrx;
import com.mp.approvalreq.util.ServiceUtils;
import com.mp.user.entity.User;
import com.plusmoney.exception.RpcServerLogicalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 审批(批准、驳回==拒绝)
 *
 * @author Administrator
 */
@WebServlet("/approveRequest")
public class ApproveRequest extends AbstractServlet {

    private static final long serialVersionUID = -6524473373623928868L;

    private static final Logger logger = LoggerFactory.getLogger(ApproveRequest.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
        doPost(req, resp);
    }

    /**
     * 数据需要为：{requestDkey:4,requestOperation:1(批准)或者2(驳回)}
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
        try {
            User user = null;

            Request request = getRequest(req);
            check(request);

            if (Objects.equals(request.getRequestOperation(), Flow.CONFIRM)
             || Objects.equals(request.getRequestOperation(), Flow.REFUSED)) {
                user = getReqUser(req);
            }

            ApprovalOperateServicePrx approvalOperateServicePrx = ServiceUtils.getApprovalOperateServicePrx();

            if (Objects.equals(request.getRequestOperation(), Flow.CONFIRM)) {
                approvalOperateServicePrx.confirmRequest(request.getRequestDkey(), user);

            } else if (Objects.equals(request.getRequestOperation(), Flow.REFUSED)) {
                approvalOperateServicePrx.refuseRequest(request.getRequestDkey(), user);
            }

            returnResult(resp);
        } catch (Throwable e) {
            onThrowable(req, resp, e);
        }
    }

    private void returnResult(HttpServletResponse resp) throws IOException {
        JSONObject jsonStr = new JSONObject();
        jsonStr.put("result", "0");
        jsonStr.put("res_info", "提交成功");
        logger.info(jsonStr.toJSONString());

        printJson(resp, jsonStr.toJSONString());
    }

    private Request getRequest(HttpServletRequest req) throws IOException {
        String reqBody = getContent(req);
        logger.info("json参数 {}", reqBody);

        Request request;
        try {
            request = JSONObject.parseObject(reqBody, Request.class);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RpcServerLogicalException(1, "审批内容提交失败，请稍候再试");
        }

        return request;
    }

    private void check(Request request) {
        if (request == null) {
            throw new RpcServerLogicalException(1, "客户端参数不能为空");
        }

        if (request.getRequestDkey() == 0) {
            throw new RpcServerLogicalException(1, "请求id不正确");
        }
    }
}
